<?php

declare(strict_types=1);

namespace app\service;

use app\enum\errcode\ErrCodeEnum;
use app\model\UserModel;
use app\param\UserParam;
use Dsxwk\Framework\Utils\Exception\CodeException;
use Dsxwk\Framework\LaravelHelper\Param\PageDataParam;
use Dsxwk\Framework\WebmanHelper\Redis\Redis;
use support\Db;
use Illuminate\Database\Eloquent\Model;
use Workbunny\WebmanCoroutine\Utils\Coroutine\Coroutine;
use Workbunny\WebmanCoroutine\Utils\WaitGroup\WaitGroup;

class UserService
{
    /**
     * 列表
     *
     * @return PageDataParam
     */
    public function index(): PageDataParam
    {
//        $config = config('database.connections.mysql');
//        $data = Db::table('user')->get();
        $waitGroup = new WaitGroup();
        $waitGroup->add();
        new Coroutine(function() use ($waitGroup) {
//            sleep(1);
            echo "Task 1 done\n";
            $waitGroup->done();
        });

        $waitGroup->add();
        new Coroutine(function() use ($waitGroup) {
//            sleep(2);
            echo "Task 2 done\n";
            $waitGroup->done();
        });

        foreach (range(3, 6) as $i) {
            $waitGroup->add();
            new Coroutine(function() use ($waitGroup, $i) {
                echo "Task $i done\n";
                $waitGroup->done();
            });
        }

        $waitGroup->wait();

        return UserModel::query()->pageData();
    }

    /**
     * 创建
     *
     * @param UserParam $param
     *
     * @return UserModel|Model
     */
    public function create(UserParam $param): Model|UserModel
    {
        return UserModel::query()->create($param->toArray());
    }

    /**
     * 异常测试
     *
     * @return mixed
     * @throws CodeException
     */
    public function exception(): mixed
    {
        UserModel::query()->first();
        UserModel::query()->orderByDesc('id')->first();
        Redis::set('test', 'test', 20);
        Redis::get('test');

        return throwError(ErrCodeEnum::INTERNAL_SERVER_ERROR);
    }
}